let questionId = null;
let answerId = null;
let vditor = null;
let user = null;
let oldAnswer = null;

function initNewAnswer() {
    let newAnswerElement = document.getElementById("new-answer");
    newAnswerElement.style.display = "block";
    newAnswerElement.addEventListener("click", async function () {
        let answerContent = vditor.getValue();
        if (answerContent.trim().length === 0) {
            parent.layui.layer.alert("回答内容不能为空！");
            return;
        }
        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能发表回答！`);
            return;
        }
        if (user.role !== "RESPONDER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有权限发表回答！`);
            return;
        }

        // 创建要发送的 JSON 数据
        const answer = {
            questionId: parseInt(questionId),
            userId: user.id,
            content: answerContent
        };
        try {
            // 使用 fetch API 发送 POST 请求
            const response = await fetch('/api/answer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(answer)
            });

            if (!response.ok) {
                parent.layui.layer.alert(`由于网络原因，新增回答失败！状态码：` + response.statusText);
                throw new Error('Network response was not ok ' + response.statusText);
            }

            const result = await response.json();

            // 根据返回结果进行处理，显示成功信息
            parent.layui.layer.alert(`新增回答成功！`);

            let answerWindow = parent.document.getElementById("answer-iframe").contentWindow;
            answerWindow.initAnswer(questionId)
            // 关闭弹窗
            var index = parent.layui.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layui.layer.close(index);

        } catch (error) {
            parent.layui.layer.alert(`新增回答出错！` + error);
            console.error('新增回答出错 There was a problem with the fetch operation:', error);
        }
    });
}

async function initOldAnswer() {
    await fetch(`/api/answer/${answerId}`)
        .then(response => {
            if (!response.ok) {
                parent.layui.layer.alert(`获取回答出错！<br />状态码：${response.status}`);
                return;
            }
            return response.json();
        })
        .then(data => {
            oldAnswer = data;
            vditor.setValue(oldAnswer.content)
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取回答失败！');
            console.error('Error:', error);
        });
}

async function initEditAnswer() {
    await initOldAnswer();
    if (!oldAnswer) {
        vditor.setValue("# 获取回答出错，请稍后重试！");
        return;
    }
    let editAnswerElement = document.getElementById("edit-answer");
    editAnswerElement.style.display = "block";
    editAnswerElement.addEventListener("click", async function () {
        let answerContent = vditor.getValue();
        if (answerContent.trim().length === 0) {
            parent.layui.layer.alert("回答内容不能为空！");
            return;
        }
        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能修改回答！`);
            return;
        }
        if (user.role !== "RESPONDER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有权限修改回答！`);
            return;
        }
        // 创建要发送的 JSON 数据
        const answer = {
            id: answerId,
            content: answerContent
        };
        try {
            // 使用 fetch API 发送 POST 请求
            const response = await fetch('/api/answer', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(answer)
            });

            if (!response.ok) {
                parent.layui.layer.alert(`由于网络原因，修改回答失败！状态码：` + response.statusText);
                throw new Error('Network response was not ok ' + response.statusText);
            }

            const result = await response.json();

            // 根据返回结果进行处理，显示成功信息
            parent.layui.layer.alert(`修改回答成功！`);

            let answerWindow = parent.document.getElementById("answer-iframe").contentWindow;
            answerWindow.initAnswer(questionId)
            // 关闭弹窗
            var index = parent.layui.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layui.layer.close(index);

        } catch (error) {
            parent.layui.layer.alert(`修改回答出错！` + error);
            console.error('修改回答出错 There was a problem with the fetch operation:', error);
        }
    });

}

function initVditor() {
    vditor = new Vditor('vditor', {
        height: "100%",
        placeholder: '请输入回答内容',
        cache: {
            enable: false
        },
        after: function () {
            questionId = getQueryVariable("question-id");
            if (!questionId) {
                vditor.setValue('<h1 style="color: red">找不到问题 ID, 请重新打开本页面！</h1>');
            }
            answerId = getQueryVariable("answer-id");
            if (answerId) {
                initEditAnswer();
            } else {
                initNewAnswer();
            }
        },
        // input: function (value) {
        //     document.getElementById("submit-answer").disabled = value.length === 0;
        // }
    });
}


async function initUser() {
    return await fetch('/api/auth/user')
        .then(response => {

            if (!response.ok && (response.status < 400 && response.status >= 500)) {
                parent.layui.layer.alert(`获取当前用户信息出错！<br />状态码：${response.status}`);
                return false;
            }

            if (!response.ok) {
                parent.layui.layer.alert(`当前您未登录！`);
                return false;
            }

            response.json().then(data => {
                user = data;
            });

            return true;
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取用户信息失败！');
            console.error('Error:', error);
            return false;
        });
}

document.addEventListener('DOMContentLoaded', () => {
    layui.use(async function () {
        initVditor();
        await initUser();
    });
});
